<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 月度任务模型
 * Class ArticleModel
 * @package app\common\model
 */
class ReadingTask extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'reading_task';

    /**
     * 阅读阅读任务
     * @param user_id 用户id
     * @param task_id 阅读任务id
     * @param database_id 数据库id
     * @param type 类型  1 作品  2 电子书
     * @param works_id 作品id
     * @param ebook_id 作品id
     */
    public function readingTaskReading($user_id, $account_id, $task_id, $database_id, $type, $works_id, $ebook_id)
    {
        $readingTaskExecuteModel = new ReadingTaskExecute();
        $readingTaskExecuteDatabaseModel = new ReadingTaskExecuteDatabase();
        $readingTaskExecuteWorksModel = new ReadingTaskExecuteWorks();
        $readingTaskExecuteWorksModel->addReadingWorks($user_id, $task_id, $database_id, $type, $works_id, $ebook_id);
        $readingTaskExecuteDatabaseModel->readingTaskDatabaseProgress($user_id, $task_id, $database_id); //更新数据库进度
        $progress = $readingTaskExecuteModel->readingTaskProgress($user_id, $account_id, $task_id); //更新总进度
        return $progress;
    }



    /**
     * 列表
     * @param limit int 分页大小
     * @param user_id string 用户id，用于查看某个用户的阅读任务
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 任务开始时间    数据格式  年月日
     * @param end_time datetime 任务结束时间
     * @param create_start_time datetime 任务创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 任务创建结束时间
     */
    public function lists($field, $keywords, $user_id, $is_play, $start_time, $end_time, $create_start_time, $create_end_time, $limit = 10)
    {
        if (empty($field)) {
            $field = [
                'id', 'title', 'img', 'start_time', 'end_time', 'browse_num', 'intro', 'is_appoint', 'is_reader', 'is_play', 'create_time'
            ];
        }
        //查询指定用户的阅读任务id
        $user_task_id = [];
        if ($user_id) {
            $user_task_id = ReadingTaskAppointUser::where('user_id', $user_id)->pluck('task_id');
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($is_play, $start_time, $end_time, $create_start_time, $create_end_time) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('start_time', [$start_time, $end_time]);
                }
                if ($create_start_time && $create_end_time) {
                    $query->whereBetween('create_time', [$create_start_time, $create_end_time]);
                }
            })
            ->where(function ($query) use ($user_id, $user_task_id) {
                if ($user_id) {
                    $query->whereIn('id', $user_task_id)->orWhere('is_appoint', 2); //指定或不指定
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('end_time')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);
        return $res;
    }

    /**
     * 详情
     * @param id int 直播id 或 二维码 token值
     */
    public function detail($id, $field = null)
    {
        if (empty($field)) {
            $field = [
                'id', 'title', 'img', 'start_time', 'end_time', 'browse_num', 'intro', 'is_appoint', 'is_reader', 'is_play', 'create_time'
            ];
        }
        $res = $this->select($field)
            ->where('id', $id)
            ->where('is_del', 1)
            ->first();

        return $res;
    }

    /**
     * 判断用户是否可以参加阅读任务
     * @param task_id 任务id
     * @param user_id 用户id
     * @param data 任务数据
     */
    public function userIsCanApply($task_id, $user_id, $data = null)
    {
        if (empty($data)) {
            $data = $this->detail($task_id);
        }
        if ($data['start_time'] > date('Y-m-d H:i:s')) {
            return false;
        }
        if ($data['end_time'] < date('Y-m-d H:i:s')) {
            return false;
        }
        if ($data['is_appoint'] == 2) {
            return true; //不指定就是都可以参加
        }
        //判断指定用户是否可以参加
        $readingTaskAppointUserModel = new ReadingTaskAppointUser();
        $appoint_user = $readingTaskAppointUserModel->getAppointUser($task_id, $user_id);
        if (empty($appoint_user)) {
            return false; //不存在就不允许参加
        }
        return true;
    }


    /**
     * 判断接口是否可以上传回复
     * @param task_id 任务id
     */
    public function apiIsCanApply($task_id)
    {
        $data = $this->detail($task_id, null, ['id', 'start_time', 'end_time']);

        if (empty($data)) {
            return '阅读任务不存在';
        }
        if ($data['start_time'] > date('Y-m-d H:i:s')) {
            return '阅读任务未开始';
        }
        if ($data['end_time'] < date('Y-m-d H:i:s')) {
            return '阅读任务已结束';
        }
        return $data->toArray();
    }


    /**
     * 获取任务状态
     * $data 任务数组
     * 
     * $status 1.任务未开始  2 任务进行中  3 任务已结束 
     */
    public function getReadingTaskStatus($data)
    {
        $time = date('Y-m-d H:i:s');
        if ($data['start_time'] > $time) {
            $status = 1;
        } else if ($data['start_time'] < $time && $data['end_time'] > $time) {
            $status = 2;
        } else {
            $status = 3;
        }
        return $status;
    }
}
